/*
 * Proja - project management software
 * Copyright (C) 2012  Oleg Kasian
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package org.proja.core.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.proja.core.entity.AbstractEntity;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractDao<T extends AbstractEntity> {

    private Class<T> clazz;

    @Autowired
    private SessionFactory sessionFactory;

    public void setClazz(final Class<T> entityClass) {
        this.clazz = entityClass;
    }

    protected final Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public T find(final Long id) {
        return (T) getCurrentSession().get(this.clazz, id);
    }

    public List<T> findAll() {
        return getCurrentSession().createQuery(" from " + this.clazz.getName()).list();
    }

    public void add(final T entity) {
        getCurrentSession().persist(entity);
        flush();
    }

    public void update(final T entity) {
        getCurrentSession().merge(entity);
        flush();
    }

    public void remove(final T entity) {
        getCurrentSession().delete(entity);
        flush();
    }

    public void flush() {
        this.getCurrentSession().flush();
    }
}